package com.niit.white_box.controller;

import com.niit.white_box.common.Result;
import com.niit.white_box.dto.LoginRequest;
import com.niit.white_box.dto.ResetByPhoneRequest;
import com.niit.white_box.dto.RegisterRequest;
import com.niit.white_box.dto.SendCodeRequest;
import com.niit.white_box.entity.User;
import com.niit.white_box.service.UserService;
import com.niit.white_box.service.SmsService;
import com.niit.white_box.service.SmsCodeStore;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin(origins = "http://localhost:8080", allowCredentials = "true")
public class WebController {

    @Resource
    UserService userService;
    @Resource
    SmsService smsService;
    @Resource
    SmsCodeStore smsCodeStore;
    @PostMapping("/login")
    public Result login(@RequestBody LoginRequest loginRequest) {
        String password = loginRequest.getPassword();
        User user = userService.login(loginRequest);
        if (user == null) {
            return Result.fail("登陆失败，请检查输入的信息");
        }
        if (user.getPassword().equals(password)) {
            return Result.success(user);
        }
        return Result.fail("登录失败：账号或密码错误");
    }

    @PostMapping("/register")
    public Result register(@RequestBody RegisterRequest registerRequest) {
        try {
            userService.register(registerRequest);
            return Result.success("注册成功");
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    // 分页用户列表
    @GetMapping("/userList")
    public Result userList(@RequestParam(name = "page", defaultValue = "1") int page,
                           @RequestParam(name = "size", defaultValue = "10") int size,
                           @RequestParam(name = "username", required = false) String username,
                           @RequestParam(name = "nickname", required = false) String nickname,
                           @RequestParam(name = "phone", required = false) String phone,
                           @RequestParam(name = "status", required = false) String status,
                           @RequestParam(name = "startDate", required = false) String startDate,
                           @RequestParam(name = "endDate", required = false) String endDate) {
        return Result.success(userService.pageUsers(page, size, username, nickname, phone, status, startDate, endDate));
    }
    
    // 根据ID获取用户
    @GetMapping("/user/{id}")
    public Result getUserById(@PathVariable int id) {
        try {
            User user = userService.getUserById(id);
            if (user == null) {
                return Result.fail("用户不存在");
            }
            // 直接返回用户对象，不要嵌套
            Result result = new Result();
            result.setSuccess(true);
            result.setCode(200);
            result.setMessage("success");
            result.getData().put("user", user);
            return result;
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }
    
    // 新增用户
    @PostMapping("/user/add")
    public Result addUser(@RequestBody User user) {
        try {
            userService.addUser(user);
            return Result.success("添加用户成功");
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }
    
    // 更新用户
    @PutMapping("/user/update")
    public Result updateUser(@RequestBody java.util.Map<String, Object> requestData) {
        try {
            User user = new User();
            
            // 检查并设置ID
            if (requestData.get("id") != null) {
                user.setId(((Number) requestData.get("id")).intValue());
            } else {
                return Result.fail("用户ID不能为空");
            }
            
            // 设置其他字段
            if (requestData.containsKey("username")) {
                user.setUsername((String) requestData.get("username"));
            }
            if (requestData.containsKey("nickname")) {
                user.setNickname((String) requestData.get("nickname"));
            }
            if (requestData.containsKey("email")) {
                user.setEmail((String) requestData.get("email"));
            }
            if (requestData.containsKey("phone")) {
                user.setPhone((String) requestData.get("phone"));
            }
            if (requestData.containsKey("gender") && requestData.get("gender") != null) {
                user.setGender(((Number) requestData.get("gender")).intValue());
            }
            if (requestData.containsKey("status") && requestData.get("status") != null) {
                user.setStatus(((Number) requestData.get("status")).intValue());
            }
            
            userService.updateUser(user);
            return Result.success("更新用户成功");
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }
    
    // 删除用户
    @DeleteMapping("/user/{id}")
    public Result deleteUser(@PathVariable int id) {
        try {
            userService.deleteUser(id);
            return Result.success("删除用户成功");
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }
    
    // 修改密码
    @PostMapping("/user/changePassword")
    public Result changePassword(@RequestBody java.util.Map<String, Object> requestData) {
        try {
            if (requestData.get("id") == null) {
                return Result.fail("用户ID不能为空");
            }
            if (requestData.get("newPassword") == null || requestData.get("newPassword").toString().trim().isEmpty()) {
                return Result.fail("新密码不能为空");
            }
            
            int userId = ((Number) requestData.get("id")).intValue();
            String newPassword = requestData.get("newPassword").toString();
            
            userService.updatePasswordById(userId, newPassword);
            return Result.success("密码修改成功");
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    @PostMapping("/sendSmsCode")
    public Result sendSmsCode(@RequestBody SendCodeRequest req) {
        String phone = req.getPhone();
        if (phone == null || !phone.matches("^\\d{11}$")) {
            return Result.fail("手机号格式不正确");
        }
        try {
            // 统一响应，不暴露存在性
            String code = smsService.generate6DigitCode();
            smsCodeStore.saveCode(phone, code, 300);
            smsService.sendResetCode(phone, code);
            return Result.success("验证码已发送");
        } catch (Exception e) {
            return Result.success("验证码已发送");
        }
    }

    @PostMapping("/verifySmsCode")
    public Result verifySmsCode(@RequestBody ResetByPhoneRequest req) {
        boolean ok = smsCodeStore.verifyCode(req.getPhone(), req.getCode());
        if (ok) return Result.success("验证码有效");
        return Result.fail("验证码无效或已过期");
    }

    @PostMapping("/resetPasswordByPhone")
    public Result resetPasswordByPhone(@RequestBody ResetByPhoneRequest req) {
        if (req.getPhone() == null || req.getCode() == null || req.getNewPassword() == null) {
            return Result.fail("参数不完整");
        }
        if (!smsCodeStore.verifyCode(req.getPhone(), req.getCode())) {
            return Result.fail("验证码无效或已过期");
        }
        try {
            userService.resetPasswordByPhone(req.getPhone(), req.getNewPassword());
            smsCodeStore.deleteCode(req.getPhone());
            return Result.success("重置成功");
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }
}
